package ch04;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisAPI {

    JedisPool jedisPool ;// 线程安全
    String host="127.0.0.1";
    String pwd ="123456";
    Integer port =6379;
    int index=0;

    public JedisAPI() {
        JedisPoolConfig config =new JedisPoolConfig();
        config.setMaxTotal(50);
        config.setMaxIdle(10);
        config.setMinIdle(7);
        config.setMaxWaitMillis(1000);
        config.setTestOnBorrow(true);

        jedisPool =new JedisPool(config
                                ,host
                                ,port
                                ,10000
                                ,pwd
                                ,index
        );
    }

    public void destory(){
        //if (null !=jedisPool || !jedisPool.isClosed())
        if (!(jedisPool==null || jedisPool.isClosed())){
            jedisPool.isClosed();
        }
    }

    public Long set(String key,String val,int second){
        Jedis jedis = null;

        try {
            jedis=jedisPool.getResource();
            jedis.set(key,val);
            jedis.expire(key,second) ;//设置失效时间
            return jedis.ttl(key);
        } catch (Exception exception) {
            exception.printStackTrace();
            return -2L;
        } finally {
            if (null!=jedis){
                jedis.close(); //释放资源,把连接放回连接池
            }
        }

    }

    public String get(String key){
        Jedis jedis =null;
        try {
            jedis=jedisPool.getResource();
            return jedis.get(key);
        } catch (Exception exception) {
            exception.printStackTrace();
            return "";
        } finally {
            if (null!=jedis) jedis.close();
        }
    }


    public String mset(String...values){
        Jedis jedis = jedisPool.getResource();
        return jedis.mset(values);
    }

    public Long append(String key , String append){

        Jedis jedis = jedisPool.getResource();
        if (jedis.exists(key)){
            return jedis.append(key ,append);
        }

        return null;
    }

    public boolean exists(Jedis jedis,String key){
        return jedis.exists(key);
    }

}
